package com.spring.framework.webmvc.servlet;

import com.spring.framework.annotation.*;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URL;
import java.util.*;

/**
 * @author ππ
 * @date 2020-11-16 10:51
 * @desc 声明servlet,主要职责是委派和分发，在1.0版本中，所有的都在servlet中实现
 */

public class MyDispatcherServletBak extends HttpServlet {
    private Properties property = new Properties();
    /**扫描文件*/
    private List<String> registryBeanClasses = new ArrayList<>();
    /**存储原生对象,Spring源码中分为BeanWrapper与Object*/
    private Map<String,Object> factoryBeanObjectCache = new HashMap<>();
    /**存储方法路径映射*/
    private Map<String,Method> handlerMappings = new HashMap<>();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            doDispatch(req,resp);
        } catch (Exception e) {
            e.printStackTrace();
            resp.getWriter().write("500");
        }
    }

    private void doDispatch(HttpServletRequest req, HttpServletResponse resp) throws IOException, InvocationTargetException, IllegalAccessException {
        // 获取请求路径
        String url = req.getRequestURI();
        String contextPath = req.getContextPath();
        url = url.replaceAll(contextPath,"");
        Method method = this.handlerMappings.get(url);
        if (method == null) {
            resp.getWriter().write("404");
        }
        // 获取请求参数
        Map<String,String[]> parameterMap = req.getParameterMap();
        //获取方法形参
        Class<?>[] parameterTypes = method.getParameterTypes();
        //设定实参
        Object[] parameterValues = new Object[parameterTypes.length];

        Annotation[][] annotations = method.getParameterAnnotations();

        for (int i = 0; i< parameterTypes.length; i++) {
            if(parameterTypes[i] == HttpServletRequest.class) {
                parameterValues[i] = req;
            } else if (parameterTypes[i] == HttpServletResponse.class) {
                parameterValues[i] = resp;
            //1.0版本中，不考虑HandlerAdapter
            } else if (parameterTypes[i] == String.class) {
                for (Annotation a : annotations[i]) {
                    if(a instanceof MyRequestParam) {
                        String parameterName = ((MyRequestParam) a).value().trim();
                        String parameterValue = Arrays.toString(parameterMap.get(parameterName))
                                .replaceAll("\\[|\\]","");
                        parameterValues[i] = parameterValue;
                    }
                }
            }
        }
        // 暂时硬编码
        String beanName = toLowerCaseFirstLetter(method.getDeclaringClass().getSimpleName());
        method.invoke(this.factoryBeanObjectCache.get(beanName),parameterValues);
    }

    @Override
    public void init(ServletConfig config) throws ServletException {
       try {
           //1、加载配置文件.Spring中对于classpath的处理采用策略模式，此处简单处理
           doLoadConfig(config.getInitParameter("configLocations"));
           //2、扫描文件
           doScanner(property.getProperty("scan-package"));
           //3、初始化IoC容器，并进行扫描文件实例化
           doInstance();
           //4、执行DI
           doAutowired();
           //5、初始化HandlerMapping
           doInitHandlerMapping();
           System.out.println("Spring framework is init");
       } catch (Exception e) {
           e.printStackTrace();
       }
    }
    private void doLoadConfig(String configLocation) {
        InputStream is = null;
        try {
            is = this.getClass().getClassLoader().getResourceAsStream(configLocation.replaceAll("classpath:",""));
            property.load(is);
        }catch (Exception e) {
            e.printStackTrace();
        }finally {
            if(is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    private void doScanner(String scanPackage) throws Exception {
        URL url = this.getClass().getClassLoader().getResource("/" + scanPackage.replaceAll("\\.","/"));
        File parent = new File(url.getFile());
        if(parent ==null) {
            throw new Exception("The Settings Of scan-package error!");
        } else {
            // 循环目录下的文件
            for (File file : parent.listFiles()) {
                // 如果仍是目录，则进行递归循环
                if(file.isDirectory()) {
                    doScanner(scanPackage + "." +file.getName());
                } else {
                    // 如果不是Class文件，则不予处理
                    if(!file.getName().endsWith(".class")) {
                        continue;
                    } else {
                        // 将扫描文件保存到缓存中
                        registryBeanClasses.add((scanPackage + "." +file.getName()).replace(".class",""));
                    }
                }
            }
        }
    }
    private void doInstance() {
        if(registryBeanClasses.isEmpty()) {
            return;
        }
        // 循环扫描文件，反射生成实例
        try {
            for (String className : registryBeanClasses) {
                Class<?> clazz = Class.forName(className);
                //获取配置的beanName，若不存在则默认类名首字母小写
                if (clazz.isAnnotationPresent(MyController.class)) {
                    String beanName = clazz.getAnnotation(MyController.class).value().trim();
                    if ("".equals(beanName)) {
                        beanName = toLowerCaseFirstLetter(clazz.getSimpleName());
                    }
                    if(factoryBeanObjectCache.containsKey(beanName)) {
                        throw new Exception("The " +beanName + " has already exist!!!" );
                    }
                    Object instance = clazz.newInstance();
                    factoryBeanObjectCache.put(beanName,instance);
                } else if (clazz.isAnnotationPresent(MyService.class)) {
                    String beanName = clazz.getAnnotation(MyService.class).value().trim();
                    if ("".equals(beanName)) {
                        beanName = toLowerCaseFirstLetter(clazz.getSimpleName());
                    }
                    if(factoryBeanObjectCache.containsKey(beanName)) {
                        throw new Exception("The " +beanName + " has already exist!!!" );
                    }
                    Object instance = clazz.newInstance();
                    factoryBeanObjectCache.put(beanName,instance);
                    // service 需要考虑接口
                    for (Class i : clazz.getInterfaces()) {
                        if (factoryBeanObjectCache.containsKey(i.getName())) {
                            throw new Exception("The " + i.getName() +" has already exist!!!");
                        }
                        factoryBeanObjectCache.put(i.getName(),instance);
                    }

                } else {
                    continue;
                }
            }
        }catch (Exception e) {
            e.printStackTrace();
        }
    }
    private void doAutowired() {
        if(this.factoryBeanObjectCache.isEmpty()) {
            return;
        }
        for(Map.Entry<String,Object> entry : factoryBeanObjectCache.entrySet()) {
            Object instance = entry.getValue();
            Class<?> clazz = instance.getClass();
            // 如果不是@MyController标识的类，则不予处理
            if (!clazz.isAnnotationPresent(MyController.class)) {
                continue;
            }
            // 遍历所有属性
            for (Field field : clazz.getDeclaredFields()) {
                // 只处理具有@MyAutowired标识的属性
                if (!field.isAnnotationPresent(MyAutowired.class)) {
                    continue;
                }
                String autowiredBeanName = field.getAnnotation(MyAutowired.class).value().trim();
                // 如果没有设定属性名，则默认为接口名称
                // 这地方是简化处理
                if("".equals(autowiredBeanName)) {
                    autowiredBeanName = field.getType().getName();
                }
                // 设置强制访问
                field.setAccessible(true);
                Object obj = this.factoryBeanObjectCache.get(autowiredBeanName);
                try {
                    field.set(instance,obj);
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    private void doInitHandlerMapping() {
        if (this.factoryBeanObjectCache.isEmpty()) {
            return;
        }
        for(Map.Entry<String,Object> entry : this.factoryBeanObjectCache.entrySet()) {
            Object instance = entry.getValue();
            Class<?> clazz = instance.getClass();
            // 只处理具有@MyController注解的类
            if (clazz.isAnnotationPresent(MyController.class)) {
                String baseUrl = "";
                if (clazz.isAnnotationPresent(MyRequestMapping.class)) {
                    baseUrl = clazz.getAnnotation(MyRequestMapping.class).value().trim();
                }
                // 遍历public修饰的方法
                for (Method method : clazz.getMethods()) {
                    if (method.isAnnotationPresent(MyRequestMapping.class)) {
                        String url = (baseUrl + "/" + method.getAnnotation(MyRequestMapping.class).value().trim()).replaceAll("/+","/");
                        handlerMappings.put(url,method);
                        System.out.println("Mapped: " +url + "," +method);
                    }
                }
            }
        }
    }

    private String toLowerCaseFirstLetter(String simpleName) {
        char[] chars = simpleName.toCharArray();
        chars[0]+=32;
        return new String(chars);
    }
}
